package icu.groot.alan.service.impl;

import icu.groot.alan.dao.UserDao;
import icu.groot.alan.dao.impl.UserDaoImpl;
import icu.groot.alan.entity.*;
import icu.groot.alan.service.UserService;
import icu.groot.alan.util.Dao;
import icu.groot.alan.util.R;
import icu.groot.alan.util.Token;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Logger;

public class UserServiceImpl implements UserService {
    Logger logger = Logger.getLogger("icu.groot.alan.service.impl.UserServiceImpl");
    UserDao userDao = new UserDaoImpl();

    @Override
    public R login(String code, String password) {
        int codeInt = 0;
        try {
            codeInt = Integer.parseInt(code);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("参数格式错误");
        }
        Connection connection = Dao.getConnection();
        //查询数据库
        LoginUser login = userDao.login(codeInt, connection);
        //校验用户
        if (login == null) return R.error("用户名错误");
        if (!login.getPassword().equals(password)) return R.error("密码错误");
        //设置token实体类
        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setCode(Integer.toString(login.getCode()));
        tokenEntity.setUserName(login.getUserName());
        tokenEntity.setDepartment(login.getDepartment());
        tokenEntity.setIntroduction(login.getIntroduction());

        //获取token
        String token = Token.generateToken(tokenEntity.getToMap());
        //打印token
        logger.info("token = " + token);
        //关闭资源连接
        Dao.closeResource(connection);
        return R.ok("登录成功").put(token);
    }

    @Override
    public OneselfUser oneself(TokenEntity tokenEntity) {
        Connection connection = Dao.getConnection();
        OneselfUser oneselfUser = userDao.oneself(Integer.parseInt(tokenEntity.getCode()), connection);
        Dao.closeResource(connection);
        return oneselfUser;
    }

    @Override
    public List<String> getDepartmentByCode(int code) {
        Connection connection = Dao.getConnection();
        List<String> department = userDao.getDepartmentByCode(connection, code);
        Dao.closeResource(connection);
        return department;
    }

    @Override
    public void paging(Paging<OneselfUser> paging) {
        Connection connection = Dao.getConnection();
        int rowCount = userDao.getCount(connection, paging.getFuzzyQuery(), paging.getDepartmentId());
        paging.setPageCount((int) Math.ceil((double)rowCount / (double) paging.getPageSize()));
        paging.setRowCount(rowCount);
        userDao.paging(paging, connection);
        Dao.closeResource(connection);
    }

    @Override
    public R add(String name, String gender, String birthDate, String jobTitle, String education, String degree, String qq, String email, String introduction, String departmentId) {
        Connection connection = Dao.getConnection();
        try {
            int updateRow = userDao.add(name, gender, birthDate, jobTitle, education, degree, qq, email, introduction, departmentId, "000000", connection);
            connection.commit();
            System.out.println(updateRow);
            if (updateRow <= 0) throw new RuntimeException("返回修改行数不大于0");
        }catch (Exception e){
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                e.printStackTrace();
            }
            return R.error("系统异常,请联系管理员");
        }
        Dao.closeResource(connection);
        return R.ok("数据插入成功");
    }

    @Override
    public R deleted(HttpServletRequest req, HttpServletResponse resp, String codes) {
        Connection connection = Dao.getConnection();
        String[] codeArrStr = codes.split(",");
        System.out.println(codes);
        System.out.println(codeArrStr);
        int[] codeArrInt = new int[codeArrStr.length];
        int updateRow = 0;
        try {
            for (int i = 0; i < codeArrStr.length; i++) {
                codeArrInt[i] = Integer.parseInt(codeArrStr[i]);
                if (codeArrInt[i] == 10000001) return R.error("不能删除系统管理员");
                //如果删除自己,那么清除cookie
                Cookie[] cookies = req.getCookies();
                if (cookies != null && ((TokenEntity) req.getAttribute("tokenEntity")).getCode().equals("10000001")){
                    for(Cookie cookie: cookies){
                        cookie.setMaxAge(0);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }
                }
            }
            updateRow = userDao.deleted(connection, codeArrInt);
            if (updateRow != codeArrInt.length) throw new RuntimeException("删除数量和传入的数量不相等,请联系管理员纠正数据");
            connection.commit();
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                e.printStackTrace();
            }
            e.printStackTrace();
            return R.error("系统异常,请联系管理员");
        }
        Dao.closeResource(connection);
        return R.ok("已删除" + updateRow + "条数据");
    }

    @Override
    public R getUserById(String code) {
        Connection connection = Dao.getConnection();
        int codeInt = -1;
        OneselfUser userByCode = null;
        try {
            codeInt = Integer.parseInt(code);
            userByCode = userDao.getUserByCode(connection, codeInt);
            logger.info(userByCode.toString());
        }catch (Exception e){
            e.printStackTrace();
            return R.error("参数格式不对,联系管理员");
        }
        return R.ok("获取数据成功").put(userByCode);

    }

    @Override
    public R updateUserByCode(String code, String name, String gender, String birthDate, String jobTitle, String education, String degree, String qq, String email, String introduction, String departmentId, String password) {
        Connection connection = Dao.getConnection();
        try {
            int updateRow = userDao.updateUserByCode(connection, Integer.parseInt(code), name, gender, birthDate, jobTitle, education, degree, qq, email, introduction, departmentId, password);
            connection.commit();
            if (updateRow <= 0) throw new RuntimeException("修改行数小于等于1");
        }catch (Exception e){
            try {
                connection.rollback();
            } catch (SQLException ex) {
                e.printStackTrace();
                throw new RuntimeException(ex);
            }
            e.printStackTrace();
            return R.error("系统异常,请联系管理员");
        }
        Dao.closeResource(connection);
        return R.ok("修改成功");
    }
}
